<template>
  <div class="mod-config">
    <!-- 选择商品分类区域 -->
    <el-row class="cat_opt">
      <el-col>
        <el-alert show-icon title="注意: 只允许为第三级分类设置相关参数" type="warning"></el-alert>
      </el-col>
      <el-col>
        <span>选择商品分类：</span>
        <el-cascader placeholder="请选择分类" size="small" v-model="selectKeys" expand-trigger="hover" :options="categoryList"
          :props="cascaderProps" filterable clearable :change-on-select="true" @change="handleCascaderChange">
        </el-cascader>
      </el-col>
    </el-row>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" size="mini" icon="el-icon-plus" :disabled="isBtnDisable"
          @click="editDialogVisible = true">添加参数
        </el-button>
        <!-- 表格区 -->
        <el-table :data="manyTableData" border style="width: 100%"
          :row-style="{height: '36px', padding: '0px', margin: '0'}" :cell-style="{padding: '0'}"
          :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag closable v-for="(item,index) in scope.row.attrVals" :key="index"
                @close="handleTagClose(index, scope.row)">
                {{item}}
              </el-tag>
              <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                ref="inputRef" size="mini" @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
              </el-input>
              <el-button v-else class="button-new-tag" type="success" size="mini" @click="showInput(scope.row)">+ 新增
              </el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="attrName" label="参数名称"></el-table-column>
          <el-table-column prop="categoryId" label="参数所属分类"></el-table-column>
          <el-table-column fixed="right" label="操作">
            <template slot-scope="scope">
              <el-button @click="showEditDialog(scope.row.attrId)" type="primary" size="mini" icon="el-icon-edit">编辑
              </el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeById(scope.row.attrId)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" icon="el-icon-plus" size="mini" :disabled="isBtnDisable"
          @click="editDialogVisible = true">添加属性
        </el-button>
        <!-- 表格区 -->
        <el-table :data="onlyTableData" border style="width: 100%"
          :row-style="{height: '36px', padding: '0px', margin: '0'}" :cell-style="{padding: '0'}"
          :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag closable v-for="(item, index) in scope.row.attrVals" :key="index"
                @close="handleTagClose(index, scope.row)">
                {{item}}
              </el-tag>
              <el-input class="input-new-tag"  v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                ref="inputRef" size="mini" @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
              </el-input>
              <el-button v-else class="button-new-tag" type="success" size="mini" @click="showInput(scope.row)">+ 新增
              </el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="attrName" label="参数名称"></el-table-column>
          <el-table-column prop="categoryId" label="参数所属分类"></el-table-column>
          <el-table-column fixed="right" label="操作">
            <template slot-scope="scope">
              <el-button @click="showEditDialog(scope.row.attrId)" type="primary" size="mini" icon="el-icon-edit">编辑
              </el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeById(scope.row.attrId)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 修改新增对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="editDialogVisible" width="30%" @close="editDialogClosed">
      <!-- 内容主体区 -->
      <el-form :model="editAttrForm" :rules="editAttrFormRules" ref="editFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attrName">
          <el-input v-model="editAttrForm.attrName" clearable></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveAttr">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 弹窗, 新增 / 修改 -->
  </div>
</template>

<script>
  export default {
    data() {
      return {
        dataListSelections: [],
        categoryList: [],
        //级联配置
        cascaderProps: {
          value: 'categoryId',
          label: 'catName',
          children: 'children'
        },
        //保存级联选择的id
        selectKeys: [],
        //被激活页签的名称
        activeName: 'many',
        //动态参数
        manyTableData: [],
        //静态参数
        onlyTableData: [],
        editDialogVisible: false,
        attrId: '',
        editAttrForm: {
          attrName: ''
        },
        editAttrFormRules: {
          attName: [{
            required: true,
            message: '请输入属性名称',
            trigger: 'blur'
          }, {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          }],
        },
      }
    },
    computed: {
      isBtnDisable() {
        return this.selectKeys.length !== 3
      },
      categoryId() {
        if (this.selectKeys.length === 3) {
          return this.selectKeys[2]
        }
        return ''
      },
      titleText() {
        return this.activeName === 'many' ? "动态参数" : '静态属性'
      }
    },
    activated() {
      this.getCategories()
    },
    methods: {
      async getCategories() {
        const res = await this.$http({
          url: `/goods/goodscategory/getTree`,
          method: 'get',
          params: this.$http.adornParams({
            'level': 3
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.categoryList = data.data;
        }
      },
      handleCascaderChange() {
        this.getDataList()
      },
      //切换tabs
      handleTabClick(e) {
        this.getDataList()
      },
      async getDataList() {
        if (this.selectKeys.length !== 3) {
          this.selectKeys = []
          this.manyTableData = []
          this.onlyTableData = []
          return
        }
        const res = await this.$http({
          url: this.$http.adornUrl('/goods/goodsattribute/listAttr'),
          method: 'get',
          params: this.$http.adornParams({
            'categoryId': this.categoryId,
            'sel': this.activeName
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          //attrVals将字符串变数组
          data.list.forEach(item => {
            item.attrVals = item.attrVals ? item.attrVals.split(',') : []
            //控制tag标签后的input框
            item.inputValue = ''
            item.inputVisible = false
          })

          if (this.activeName === 'many') {
            this.manyTableData = data.list
          } else {
            this.onlyTableData = data.list
          }
        } else {
          this.dataList = []
        }
      },
      editDialogClosed() {
        this.attrId = ''
        this.editDialogVisible = false
        this.$refs.editFormRef.resetFields();
      },
      saveAttr() {
        this.$refs.editFormRef.validate(async valid => {
          if (valid) {
            let url = '/goods/goodsattribute/' + (this.attrId ? 'update' : 'save')
            const res = await this.$http({
              url,
              method: 'post',
              data: this.$http.adornData({
                attrName: this.editAttrForm.attrName,
                attrSel: this.activeName,
                categoryId: this.categoryId,
                attrId: this.attrId
              })
            })
            let data = res.data
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.editDialogVisible = false;
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }

          }
        });
      },
      async showEditDialog(attrId) {
        this.attrId = attrId
        const res = await this.$http({
          url: `/goods/goodsattribute/info/${attrId}`,
          method: 'get'
        })
        let data = res.data
        if (data && data.code === 0) {
          this.editAttrForm = data.goodsAttribute
          this.editDialogVisible = true
        }

      },
      removeById(attrId) {
        var ids = attrId ? [attrId] : this.dataListSelections.map(item => {
          return item.attrId
        })
        this.$confirm(`确定对[attrId=${ids.join(',')}]进行[${attrId ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http({
            url: '/goods/goodsattribute/delete',
            method: 'post',
            data: this.$http.adornData(ids, false)
          })

          let data = res.data
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      //展示文本框
      showInput(row) {
        row.inputVisible = true;
        //让文本框获得焦点，this.$nextTick表示页面渲染完成之后
        this.$nextTick(() => {
          this.$refs.inputRef.$refs.input.focus();
          this.$refs.inputRef.focus();
        });
      },
      //tag标签 input失去焦点，或按下enter键
      handleInputConfirm(row) {
        let inputValue = row.inputValue;
        if (!inputValue || inputValue.trim().length === 0) {
          row.inputVisible = false;
          row.inputValue = '';
          return
        }
        row.attrVals.push(inputValue.trim())
        row.inputVisible = false;
        row.inputValue = '';

        //保存到数据库中
        this.saveAttrVals(row)
      },
      async saveAttrVals(row) {
        const res = await this.$http({
          url: `/goods/goodsattribute/update`,
          method: 'post',
          data: this.$http.adornData({
            attrId: row.attrId,
            attrName: row.attrName,
            attrSel: row.attrSel,
            attrVals: row.attrVals.join(",")
          })
        })

        let data = res.data
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList()
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      },
      handleTagClose(index, row){
        row.attrVals.splice(index, 1)
        this.saveAttrVals(row)
      }
    }
  }
</script>
<style lang='less' scoped>
  .cat_opt {
    margin: 10px 0;
  }

  .el-table {
    margin-top: 10px
  }

  .el-cascader {
    width: 18%;
    margin-top: 10px;
  }

  .button-new-tag {
    height: 22px;
    line-height: 22px;
    padding: 0 8px;
    margin: 5px 0px 5px 15px;
  }

  .el-tag {
    margin: 5px 0px 5px 15px
  }

  .input-new-tag {
    width: 140px;
    margin: 5px 0 5px 15px;
  }
</style>
